import React, { createRef } from 'react';
import Taro from '@tarojs/taro'
import { AtButton, AtForm, AtInput, AtList, AtListItem, AtNavBar } from 'taro-ui';
import { Picker, ScrollView, View } from '@tarojs/components';
import { DatePicker } from "antd-mobile";
import config from '../../config.json'
import "./applyRoom.less"
import Calendar from '../../calendar/calendar'

function PrefixInteger(num, length) {
    return (Array(length).join('0') + num).slice(-length);
}

const formatDate = function (date: Date, fmt: string) {
    if (date === null) {
        return "";
    }
    var o = {
        "M+": date.getMonth() + 1, //月份 
        "d+": date.getDate(), //日 
        "H+": date.getHours(), //小时 
        "m+": date.getMinutes(), //分 
        "s+": date.getSeconds(), //秒 
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
        "S": date.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


type ApplyRoomState = {
    roomId: string
    date: string
    startTime: Date
    endTime: Date
    reason: string
    remark: string
    times: any[]
    date_picker_visible: boolean
    start_time_picker_visible: boolean
    end_time_picker_visible: boolean
}

class ApplyRoom extends React.Component<any, ApplyRoomState> {
    constructor(props) {
        super(props);
        this.state = {
            roomId: '',
            date: '',
            startTime: null,
            endTime: null,
            reason: '',
            remark: '',
            times: [],
            date_picker_visible: false,
            start_time_picker_visible: false,
            end_time_picker_visible: false,
        }
    }
    handleChangeTime(value, evt) {
        console.log(value, evt.detail.value);
        let obj = {};
        if (value === "date") {
            // this.loadTime(evt.detail.value);
        }
        if (value === "endTime" && !this.state.startTime) {
            Taro.showToast({
                title: "请先选择开始时间",
                icon: "none"
            });
            return;
        }
        if (value === "startTime") {
            if (!this.state.date) {
                Taro.showToast({
                    title: "请先选择日期",
                    icon: "none"
                });
                return;
            }
            let now = new Date();
            let time = new Date();
            obj[value] = evt.detail.value;
            let [year, month, date] = this.state.date.split("-");
            let [hour, min] = evt.detail.value.split(":");
            time.setDate(parseInt(date));
            time.setFullYear(parseInt(year));
            time.setHours(parseInt(hour));
            time.setMinutes(parseInt(min));
            time.setMonth(parseInt(month) - 1);
            console.log(now, time);
            if (now.getTime() > time.getTime()) {
                Taro.showToast({
                    title: "不能选择已经过去的时间",
                    icon: "none"
                });
                return;
            }
            obj["endTime"] = (parseInt(min) + 30 >= 60)
                ? `${PrefixInteger(parseInt(hour) + 1, 2)}:${PrefixInteger(parseInt(min) + 30 - 60, 2)}`
                : `${hour}:${parseInt(min) + 30}`;
            this.setState(obj);
        }

        obj[value] = evt.detail.value;
        this.setState(obj);
        return value;
    }

    async loadTime(time: Date) {
        let itime = new Date(time.getTime());
        itime.setHours(0);
        itime.setMinutes(0);
        itime.setSeconds(0);
        let timenum = itime.getTime();
        let res = await Taro.request({
            url: config.domainName + `/meetroom/query-times?mid=${Taro.getCurrentInstance().router.params.id}&time=${timenum}`,
            header: {
                token: Taro.getStorageSync('token'),
            }
        });
        this.setState({
            times: res.data.data.map((value) => {
                return {
                    start_time: new Date(value.start_time),
                    end_time: new Date(value.end_time)
                }
            })
        });
        console.log(res);
    }

    handleChangeText(value, evt) {
        console.log(value, evt);
        let obj = {};
        obj[value] = evt;
        this.setState(obj);
        return value;
    }
    onSubmit() {
        if (this.state.startTime && this.state.endTime && this.state.reason) {

            console.log(this.state);
            Taro.request({
                url: config.domainName + '/agreed/create',
                method: 'POST',
                data: {
                    mid: Taro.getCurrentInstance().router.params.id,
                    start_time: this.state.startTime.getTime(),
                    end_time: this.state.endTime.getTime(),
                    reason: this.state.reason,
                    note: this.state.remark,
                },
                header: {
                    token: Taro.getStorageSync('token'),

                },
                success(res) {
                    if (res.data.code === 0) {

                        Taro.showToast({
                            title: '已预约，待通过',
                            icon: "success"
                        })
                        setTimeout(() => {
                            Taro.navigateBack({
                                delta: 2
                            })
                        }, 500)
                        // console.log(this.state);
                    } else {
                        Taro.showToast({
                            title: res.data.msg,
                            icon: "error" as any
                        })
                    }

                },
                fail() {
                    console.log("获取失败!");
                }
            })
        } else {
            Taro.showToast({
                title: '请完整填写信息',
                icon: "none"
            })
        }

    }

    render() {
        let now = new Date();
        return (
            <AtForm>
                <AtNavBar
                    onClickLeftIcon={() => { Taro.navigateBack() }}
                    color='#000'
                    title='会议室申请'
                    leftIconType="chevron-left"
                />
                <View style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginRight: 20 }}>
                    <View className="module-title">填写申请信息</View>
                </View>
                <AtList>
                    <AtListItem
                        onClick={() => {
                            this.setState({
                                start_time_picker_visible: true
                            });
                        }}
                        title='请选择起始时间'
                        extraText={formatDate(this.state.startTime, "MM-dd HH:mm")}
                    />
                </AtList>
                <DatePicker
                    visible={this.state.start_time_picker_visible}
                    onClose={() => {
                        this.setState({ start_time_picker_visible: false });
                    }}
                    defaultValue={now}
                    min={now}
                    precision="minute"
                    onConfirm={val => {
                        this.setState({ 
                            startTime: val,
                            endTime: null
                        });
                        // this.loadTime(val);
                    }}
                />
                <AtList>
                    <AtListItem
                        title='请选择终止时间'
                        extraText={formatDate(this.state.endTime, "MM-dd HH:mm")}
                        onClick={() => {
                            if (this.state.startTime) {
                                this.setState({
                                    end_time_picker_visible: true
                                });
                            } else {
                                Taro.showToast({
                                    icon: "none",
                                    title: "请先选择开始时间"
                                })
                            }
                        }}
                    />
                </AtList>
                <DatePicker
                    visible={this.state.end_time_picker_visible}
                    onClose={() => {
                        this.setState({ end_time_picker_visible: false });
                    }}
                    defaultValue={now}
                    min={this.state.startTime ? new Date(this.state.startTime.getTime() + 1000 * 60 * 30) : now}
                    max={this.state.startTime ? getToday(this.state.startTime) : now}
                    precision="minute"
                    onConfirm={val => {
                        if (this.state.startTime) {
                            this.setState({ endTime: val });
                        } else {
                            Taro.showToast({
                                icon: "none",
                                title: "请先选择开始时间"
                            })
                        }
                    }}
                />
                <AtInput
                    title="原因:"
                    name="reason"
                    value={this.state.reason}
                    onChange={this.handleChangeText.bind(this, 'reason')}
                />
                <AtInput
                    title="备注:"
                    name="remark"
                    value={this.state.remark}
                    onChange={this.handleChangeText.bind(this, 'remark')}
                />
                {/* <TimeAxis times={this.state.times} /> */}
                <View style={{ margin: "10px 0" }}>
                    <AtButton className="submit-btn" type="primary" onClick={this.onSubmit.bind(this)} > 提交 </AtButton>
                </View>

            </AtForm>
        )
    }
}
export default ApplyRoom;


interface TimeAxisProps {
    times: {
        start_time: Date
        end_time: Date
    }[]
}

class TimeAxis extends React.Component<TimeAxisProps, any> {
    constructor(props) {
        super(props);
    }

    render() {
        let start = this.props.times[0];
        console.log(!this.props.times.length)
        return (
            <View style={{ paddingLeft: "0.7rem", paddingTop: "0.4rem", fontSize: "0.65rem", color: "#222" }}>
                <View>该日已被占用时间</View>
                <View >
                    <View className="time-axis">

                        <View className="td">
                            {(() => {
                                return this.props.times.map((value, index) => {
                                    return <View className="time">{`${value.start_time.getHours()}:${value.start_time.getMinutes() < 10 ? value.start_time.getMinutes() + "0" : value.start_time.getMinutes()}`}~{`${value.end_time.getHours()}:${value.end_time.getMinutes() < 10 ? value.end_time.getMinutes() + "0" : value.end_time.getMinutes()}`}</View>
                                })
                            })()}
                            {
                                !this.props.times.length ? <View style={{ textAlign: "left", fontSize: "0.55rem", color: "#999" }}>空</View> : ""
                            }
                        </View>
                    </View>
                </View>
            </View>
        )
    }
}

function getToday(date: Date): Date {
    let newDate = new Date(date.getTime());
    newDate.setHours(23);
    newDate.setMinutes(59);
    return newDate;
}